# -*- coding: utf-8 -*-

from app.models import Product, ProductSKU, Order, OrderItem
from mongoengine import Q
from app.utils import safe_int, get_objectId
from app.constants import form_field_dict, API_ORDER_ERROR
from app.controllers import get_productsku_blackout_date

from flask import current_app

from copy import deepcopy


class BookUtils(object):
    def get_order_form_data(self, product):

        """
        需求：用户需要编辑刚刚提交但未付款的订单
        实现：
            1， 从订单关联的产品（）中获取需要用户填写的信息，
            2， 从订单
        获取订单中，用户已经填写的信息

        """
        pcc = product.product_custom_category
        default_sku = product.get_default_sku_as_dict()
        data = {
            'basic': pcc.get('basic', {}),
            'extended': pcc.get('extended', {}),
            'contact': pcc.get('contact', {}),
            'default_sku': default_sku,
            'total_price': default_sku.get('total_price', 0.0)
        }

        return data

    def get_order_data(self, order):
        """
        需求：用户需要编辑刚刚提交但未付款的订单
        实现：
            1， 从订单关联的产品（或者Order.items）中获取需要用户填写的信息，
            2， 将订单中用户已经填写的信息填充到对应的属性
        """

        # TODO zezhou 从 订单中所关联的items 获取各个产品需要用户填写的信息
        # TODO zezhou 返回用户在该订单中的购买的items，不再是返回默认的那个

        product = order.product
        order_dict = order.as_dict()  # FIXME 重写了 base document方法, 应该利用两个方法
        custom_option_dict = order_dict.get('custom_option', {})

        basic = []
        for k in product.product_custom_category.get('basic', {}).keys():
            basic.append({k: custom_option_dict.get(k, '')})

        extended = []
        for k in product.product_custom_category.get('extended', {}).keys():
            extended.append({k: custom_option_dict.get(k, '')})

        contact = []
        for k in product.product_custom_category.get('contact', {}).keys():
            contact.append({k: custom_option_dict.get(k, '')})

        data = {
            'total_price': order.get_total_price(),
            'basic': basic,
            'extended': extended,
            'contact': contact
        }
        # TODO sort data
        return data

    def sort_dict(self, data):
        if data['extended']:
            data['extended'] = sorted(data['extended'], cmp=self.cmp, reverse=False)

        if data['contact']:
            data['contact'] = sorted(data['contact'], cmp=self.cmp, reverse=False)

    def cmp(self, x, y):
        cmp(x['sort'], y['sort'])

    def check_orders_before_pay(self, order_ids, plan=None):
        """
        检查订单是否可以支付
         目前检查字段：
            order.contact_email,
            order.info['date'] 使用日期
        """
        condition = Q(id__in=order_ids)
        if plan:
            condition &= Q(plan_id=plan)

        resp = {
            'is_correct': True
        }

        orders = Order.objects.filter(condition)
        for order in orders:
            item = {
                'order_id': str(order.id),
                'name': order.product.name,
                'destination_id': order.product.destination_id,
            }
            if not order.contact_email:
                resp['is_correct'] = False
                item['message'] = API_ORDER_ERROR.NO_DATE
                return resp

            book_date = order.info.get('date', '')
            if book_date and order.product.product_custom_category.get('use_date'):
                skus = [item.sku for item in order.items]
                resp['is_correct'] = get_productsku_blackout_date(skus, book_date=book_date)
                if not resp['is_correct']:
                    item['message'] = API_ORDER_ERROR.DATE_ERROR

            resp.update(item)
        return resp


book_utils = BookUtils()
